import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as Joi from 'joi';
import { Logger } from '@nestjs/common';
import { ConfigEnv ,EnvConfig} from './config.dto';
export class ConfigService {
  private readonly envConfig: ConfigEnv;

  constructor(filePath: string) {
    const config = dotenv.parse(fs.readFileSync(filePath));
    Logger.log(config, filePath);
    this.envConfig = this.validateInput(config);
  }
  private validateInput(envConfig: EnvConfig): ConfigEnv {
    const envVarsSchema: Joi.ObjectSchema = Joi.object({
      NODE_ENV: Joi.string()
        .valid(['development', 'production', 'test', 'provision'])
        .default('development'),
      PORT: Joi.string().default(8088),
      ORM_LOADING_PATH: Joi.string().required(),

      MYSQL_DATABASE_HOST:Joi.string(),
      MYSQL_DATABASE_PORT:Joi.number(),
      MYSQL_DATABASE_USER:Joi.string(),
      MYSQL_DATABASE_PWD:Joi.string(),
      MYSQL_DATABASE_DB:Joi.string(),
      MYSQL_DATABASE_SYNCHRONIZE: Joi.boolean(),
      MYSQL_DATABASE_DROPSCHEMA: Joi.boolean(),

      MONGODB_DATABASE_HOST:Joi.string(),
      MONGODB_DATABASE_PORT:Joi.number(),
      MONGODB_DATABASE_USER:Joi.string(),
      MONGODB_DATABASE_PWD:Joi.string(),
      MONGODB_DATABASE_DB:Joi.string(),
    });
    const { error, value: validatedEnvConfig } = Joi.validate(
      envConfig,
      envVarsSchema,
    );
    if (error) {
      throw new Error(`Config validation error: ${error.message}`);
    }
    return validatedEnvConfig;
  }
  get(key: string): any {
    return this.envConfig[key];
  }

  get env(): string {
    return this.envConfig.NODE_ENV;
  }
}
